<template>
    <div style="height: 45px;box-shadow:0px 5px 20px 0px rgba(0,0,0,0.1);padding: 0 10px;">
        <div style="float: left;font-size: 25px;line-height: 45px;">欢迎咨询</div>
        <div style="float: right;line-height: 45px;">
            <el-popconfirm
                    width="220"
                    confirm-button-text="关闭"
                    cancel-button-text="取消"
                    title="确认关闭该会话吗?"
                    @confirm = closeChat
            >
                <template #reference>
                    <el-icon v-show = chat.alive style="line-height: 45px;margin: 10px" size="30px" title="关闭会话"><Close /></el-icon>
                </template>
            </el-popconfirm>

            <div style="float: right;line-height:45px;">{{nickName}}</div>
            <el-avatar  style="float: right;height:40px;width: 40px;margin: 2px 10px" src="/zuotian.jpg" />
            <el-link v-show="!isLogined"  @click="toLogin" style="float: right;font-size: 15px;line-height: 45px;">立即登录</el-link>
        </div>
    </div>
    <el-row style="width: 100vw;" class="content">
        <el-col :span="24" style="opacity:1;">
            <div style="padding: 10px;opacity:1;">
                <!--消息框-->
                <div class ="scrollDiv" @click="" ref="msgArea" style="height:calc(100vh - 260px); overflow:auto; border: 1px solid #ccc;
                border-radius: 5px;background-color: #f5f5f5;">
                    <Messages :msgs="chat.msgs" showAt="client"/>
                </div>
                <!--消息框结束-->
                <div style="width:100%;height:20px;border:none;">
                </div><!--输入框结束-->
                <!--输入框-->
                <div v-if="chat.alive" style="height: 120px;border-radius: 5px;border:1px solid #ccc;">
                    <textarea @keydown.enter.prevent="send(chat)" style="height: 100%; width: 100%; padding-top: 10px;
                     outline: none;border: none; resize: none" v-model="chat.inputBox" />
                </div><!--输入框结束-->
                <el-button style="margin-top:10px;float:right" v-if="chat.alive" type="primary"  @click="send(chat)">发送</el-button>
            </div>
        </el-col>
    </el-row>
    <ClientLogin ref="clientLogin" @afterLogin="logined"/>
    <Satisfaction ref="satisfaction" :chatId = chat.id />
    <PlayAudio ref="playAudio"/>
</template>

<script setup>
    import {nextTick, reactive, ref, onMounted,computed} from 'vue'
    import ClientLogin from "@/views/client/ClientLogin.vue"
    import Satisfaction from "@/views/client/Satisfaction.vue"
    import Messages from '@/components/common/Messages.vue'
    import {ElMessage} from 'element-plus'
    import {Headset} from '@element-plus/icons-vue'
    import request from '@/utils/request.js'
    import moment from 'moment'
    import PlayAudio from '@/components/business/PlayAudio.vue'
    let playAudio = ref(null)
    let customer = reactive({nickName:"XX"})
    let clientLogin = ref(null)
    let isLogined = ref(false)
    let msgArea = ref()
    let chatId;
    let userId  = new Date().getTime().toString();
    let websocket =  null
    let keepalive = null
    let satisfaction = ref(null)
    onMounted(()=>{
        document.querySelector("title").text = "尤八哥咨询平台"
        // request.get(`/api/client/getChatId/${userId}`).then(resp => {
        let customer = sessionStorage.getItem("customer")
         if(!customer){
             clientLogin.value.showDialog = true
         }else{
             logined(JSON.parse(customer))
         }
        // });
    })

    function logined(cust) {
        isLogined.value = true
        chat.alive = true
        for(let key in cust){
            customer[key] = cust[key]
        }
        sessionStorage.setItem("customer", JSON.stringify(customer))
        let host = window.location.host
        websocket  = new WebSocket(`ws://${host}/socket/client/`+customer.id+"/0")

        websocket.onopen = function(){
            // getChatId(userId)
        }

        websocket.onerror = function (e) {
            ElMessage({message: "websocket连接出错", type: 'error'})
        }

        websocket.onmessage = function (event) {
            console.log(event.data)
            let msg = JSON.parse(event.data)
            if(msg.chatId != null){
                chat.id = msg.chatId
            }
            if("close" == msg.type){
                if(!chat.alive){
                    return
                }
                if(chat.id != null){
                    websocket.close()
                    satisfaction.value.showDialog = true
                }
                chat.alive = false
                if("client" == msg.sender){
                    return
                }
            }
            chat.msgs.push(msg)
            scrollerToBottom()
        }
        keepalive = setInterval(function(){
                let msg = {"type" : "keepalive"}
                websocket.send(JSON.stringify(msg))
            },
            30*1000)
    }

    let nickName = computed(() => {
        let nickName = customer.nickName
        let len =  nickName.length
        return len > 2 ? nickName.substr(len -2, len) : nickName
    })

    let chat = reactive(
        {
            alive:false,
            msgs:[
                {'content':`您好，欢迎咨询，您可以直接发送消息`,"type":"text","sender":'agent'},
                ]
        })

    function getChatId(userId){
        // request.get(`/api/client/getChatId/${userId}`).then(resp => {
        //     chatId = resp;
        // });
    }

    function send(chat){
        let content = chat.inputBox.trim()
        if(content === ""){
            ElMessage({message: "请输入内容",type: 'error'})
            return
        }
        let time = moment().format("yyyy-MM-DD HH:mm:ss")
        let msg = {"content" : content,"type" : "text", "chatId" : chatId, "senderName" : customer.nickName}
        if(WebSocket.OPEN === websocket.readyState){
            websocket.send(JSON.stringify(msg))
            // chat.msgs.push(msg)
            chat.inputBox = ""
            scrollerToBottom(chat.clientName)
        }else{
            ElMessage({message: "会话已经断开",type: 'error'})
            chat.alive = false
        }
    }

    function scrollerToBottom() {
        nextTick(function () {
            msgArea.value.scrollTop = msgArea.value.scrollHeight
        })
    }

    function closeChat() {
        let msg = {"type" : "close", "chatId" : chat.id, "senderName" : customer.nickName}
        websocket.send(JSON.stringify(msg))
        clearInterval(keepalive)
        websocket.close()
    }
    function toLogin() {
        clientLogin.value.showDialog = true
    }
</script>
<style lang="css" scoped>
    .tip {
        border-radius: 10px;
        padding: 10px;
        width:auto;
        display:inline-block !important;
        word-wrap: break-word;
        word-break: break-all;
        text-align:left;
        max-width:60%;
    }
    .system {
        font-size:10px;
    }
    .time {
        padding: 5px;
        display:inline-block;
        color: #9a9b9e;
        font-size: 13px;
    }
    .item {
        margin-top: 5px;
    }
    .right {
        background-color:  #a7e861;
    }
    .left {
        background-color:  white;
    }
    .span-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;}
    .btn-bell-badge {
        width: 26px;
        height: 18px;
        margin-left:5px;
        line-height:18px;
        border-radius: 15px;
        background: #f56c6c;}
    .num {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #fff;
    }
    .content::after{
        content: "";
        background-image: url('/zuotian.jpg');
        opacity:0.5;
    }
</style>